package com.cduestc.weatheractivity;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.CursorWrapper;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.cduestc.animation.ExitApp;
import com.cduestc.sqllite.MySqlLite;
import com.cduestc.sqllite.ShowAll;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ManageCity extends Activity implements ShowAll {

    ImageButton ibBack,ibEditCity,ibAddCity;
    ListView lvMyCity;
    private MySqlLite mySqlLite;
    SQLiteDatabase sdb;
    Handler handler = new Handler();
    SimpleAdapter scadapter;
    List list = new ArrayList();
    String result = "";
    SharedPreferences share;
    int i = 0;
    boolean f = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApp exitApp = ExitApp.getInstance();
        exitApp.addActivity(this);
        setContentView(R.layout.activity_manage_city);

        ibBack = this.findViewById(R.id.ibBack);
        ibEditCity = this.findViewById(R.id.ibEditCity);
        ibAddCity = this.findViewById(R.id.ibAddCity);
        lvMyCity = this.findViewById(R.id.lvMyCity);

        share = this.getSharedPreferences("LocalCity",MODE_PRIVATE);
        mySqlLite = new MySqlLite(this,"c1",null,1);
        sdb = mySqlLite.getWritableDatabase();

        String cityName = share.getString("TheFirst","");
        if(!cityName.equals("")){
            result = cityName;
        }
        //Log.i("result",result);
        showCitys();

        //返回
        ibBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ManageCity.this,HomePage.class);
                startActivity(intent);
                exitApp.onLowMemory();
                finish();
            }
        });

        //编辑
        ibEditCity.setOnClickListener(new View.OnClickListener() {
            String[] cityNames = new String[list.size()];

            @Override
            public void onClick(View view) {

                Cursor cursor = sdb.query("mycitys",new String[]{"_id","cid","cityname"},null,null,null,null,null);
                if(cursor.getCount() == 0){
                    Toast.makeText(ManageCity.this, "当前没有城市数据，点击下方按钮去添加", Toast.LENGTH_SHORT).show();
                    return;
                }else{
                    while (cursor.moveToNext()) {
                        int cid = cursor.getInt(0);
                        String ccId = cursor.getString(1);
                        String ccName = cursor.getString(2);

                        cityNames[i] = ccName;
                        Log.i("103",ccName);

                        i++;
                    }
                    System.out.println(cityNames.length);
                }
//                if(f == true){
//                    for (int r = 0; r < cityNames.length-1; r++){
//
//                        if(cityName.equals(cityNames[r])){
//                            i = r;
//                            break;
//                        }else{
//                            i = 0;
//                        }
//                    }
//                }else {
                    for (int r = 0; r < cityNames.length; r++) {

                        if (cityName.equals(cityNames[r])) {
                            i = r;
                            break;
                        } else {
                            i = 0;
                        }
                    }
               // }

                if(i == 0){
                    Toast.makeText(ManageCity.this, "当前没有设置首显城市", Toast.LENGTH_SHORT).show();
                }

                AlertDialog.Builder builderB = new AlertDialog.Builder(ManageCity.this);

                builderB.setIcon(android.R.drawable.ic_dialog_email)
                        .setTitle("设置首页显示城市：")
                        .setCancelable(false)
                        .setSingleChoiceItems(cityNames, i, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int p) {
                                result = cityNames[p];
                            }
                        })
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int p) {
                                if(result != null){
                                    SharedPreferences.Editor se = share.edit();
                                    se.putString("TheFirst",result);
                                    se.commit();
                                }
                                for(int k = 0; k < list.size(); k++){
                                    cityNames[k] = "";
                                }
                                i = 0;
                                Toast.makeText(ManageCity.this, "成功设置首页城市为 " + result, Toast.LENGTH_SHORT).show();

                                for(int x = 0; x < list.size();x++ ){
                                    cityNames[x] = "";
                                }
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int p) {
                                for(int k = 0; k < list.size(); k++){
                                    cityNames[k] = "";
                                }
                                i = 0;
                                dialogInterface.dismiss();
                            }
                        })
                        .create()
                        .show();
            }
        });

        //添加
        ibAddCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ManageCity.this,Search.class);
                startActivity(intent);
            }
        });

        lvMyCity.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                TextView tvCodeHere = view.findViewById(R.id.tvCode);
                String str = tvCodeHere.getText().toString().trim();
                AlertDialog.Builder builder = new AlertDialog.Builder(ManageCity.this);
                builder.setIcon(R.drawable.icon_warning)
                        .setTitle("提示")
                        .setMessage("确定删除吗?")
                        .setCancelable(false)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                if(str.equals(result)){
                                    Toast.makeText(ManageCity.this, "当前城市是首页显示城市，删除后首页显示城市也将清除", Toast.LENGTH_SHORT).show();
                                    SharedPreferences.Editor se = share.edit();
                                    se.putString("TheFirst","");
                                    se.commit();
                                }

                                sdb.delete("mycitys", "cid=?", new String[]{str});
                                Toast.makeText(ManageCity.this, "删除成功", Toast.LENGTH_SHORT).show();
                                Cursor c = sdb.query("mycitys",new String[]{"_id","cid","cityname"},null,null,null,null,null);
                                List li = new ArrayList();
                                while(c.moveToNext()){
                                    Map m = new HashMap();

                                    int cid = c.getInt(0);
                                    String ccId = c.getString(1);
                                    String ccName = c.getString(2);

                                    m.put("col1", cid);
                                    m.put("col2", ccId);
                                    m.put("col3", ccName);

                                    li.add(m);
                                }
                                updateList(li);
                                dialogInterface.dismiss();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        })
                        .create()
                        .show();
                return false;
            }
        });
    }

    @Override
    public String showCitys() {

        Cursor cursor = sdb.query("mycitys",new String[]{"_id","cid","cityname"},null,null,null,null,null);
        if(cursor.getCount() == 0){
            return "当前没有城市数据，点击下方按钮去添加";
        }else{
                while (cursor.moveToNext()) {
                    Map map = new HashMap();

                    int cid = cursor.getInt(0);
                    String ccId = cursor.getString(1);
                    String ccName = cursor.getString(2);

                    map.put("col1", cid);
                    map.put("col2", ccId);
                    map.put("col3", ccName);

                    list.add(map);

                }
            }
        scadapter = new SimpleAdapter(
                ManageCity.this,
                list,
                R.layout.manage_city_items,
                new String[]{"col1","col2","col3"},
                new int[]{R.id.tvId,R.id.tvCode,R.id.tvName}
        );
        lvMyCity.setAdapter(scadapter);

        //Log.i("1",scadapter.toString());

        return null;
    }

    @Override
    public String editCitys() {
        final int MAX_LENGTH = 50;
        int i = 0;
        int[] cids = new int[MAX_LENGTH];
        String[] ccIds = new String[MAX_LENGTH];
        String[] ccNames = new String[MAX_LENGTH];

        List list1 = new ArrayList();
        Cursor cursor = sdb.query("mycitys",new String[]{"_id","cid","cityname"},null,null,null,null,null);
        if(cursor.getCount() == 0){
            return "当前没有城市数据，点击下方按钮去添加";
        }else {
            while(cursor.moveToNext()) {

                cids[i] = cursor.getInt(0);
                ccIds[i] = cursor.getString(1);
                ccNames[i] = cursor.getString(2);

                i++;
            }
            for(int r = 0; r <= (i-1); r++){
                Map map1 = new HashMap();

                map1.put("cols1",cids[r]);
                map1.put("cols2",ccIds[r]);
                map1.put("cols3",ccNames[r]);

                list1.add(map1);
            }
        }
        SimpleAdapter scadapter1 = new SimpleAdapter(
                ManageCity.this,
                list1,
                R.layout.manage_city_items_edit,
                new String[]{"cols1","cols2","cols3"},
                new int[]{R.id.tvIdEdit,R.id.tvCodeEdit,R.id.tvNameEdit}
        );
        lvMyCity.setAdapter(scadapter1);

        return null;
    }

    //更新显示数据
    public void updateList(List list123){
        list.clear();
        list.addAll(list123);
        scadapter.notifyDataSetChanged();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            return false;
        }
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();

    }
}